// 检查登录状态
const token = localStorage.getItem('token');
if (!token) {
    window.location.href = 'index.html';
}

// 连接WebSocket
function connectWebSocket() {
    const ws = new WebSocket(`ws://localhost:8081/ws?token=${token}`);
    
    ws.onopen = function() {
        console.log('Connected to game server');
        showStatus('已连接到游戏服务器');
    };
    
    ws.onmessage = function(event) {
        const message = JSON.parse(event.data);
        handleMessage(message);
    };
    
    ws.onclose = function() {
        console.log('Disconnected from game server');
        showStatus('与游戏服务器断开连接', 'error');
        // 尝试重新连接
        setTimeout(connectWebSocket, 3000);
    };
    
    ws.onerror = function(error) {
        console.error('WebSocket error:', error);
        showStatus('连接错误', 'error');
    };

    // 添加心跳响应
    let pingTimeout;
    
    function heartbeat() {
        clearTimeout(pingTimeout);
        pingTimeout = setTimeout(() => {
            console.log('Connection lost - heartbeat timeout');
            ws.close();
        }, 60000 + 1000); // 服务器端超时时间 + 1秒
    }

    ws.addEventListener('open', heartbeat);
    ws.addEventListener('ping', heartbeat);
    ws.addEventListener('message', heartbeat);
    ws.addEventListener('close', function() {
        clearTimeout(pingTimeout);
    });
}

// 显示状态消息
function showStatus(message, type = 'info') {
    const statusDiv = document.getElementById('statusMessage');
    statusDiv.textContent = message;
    statusDiv.className = `status-message ${type}`;
    setTimeout(() => {
        statusDiv.textContent = '';
        statusDiv.className = 'status-message';
    }, 3000);
}

// 处理服务器消息
function handleMessage(message) {
    switch (message.type) {
        case 'chat':
            // 处理聊天消息
            break;
        case 'game_action':
            // 处理游戏动作
            break;
        case 'match_result':
            if (message.content.success) {
                matchStatus.textContent = '匹配成功！准备进入战斗...';
                // 关闭匹配模态框
                matchModal.style.display = 'none';
            }
            break;
        case 'battle_start':
            console.log('收到战斗开始消息:', message.content); // 添加日志
            handleBattleStart(message.content);
            break;
        case 'battle_result':
            handleBattleResult(message.content);
            break;
        // 添加更多消息类型的处理...
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载用户信息
    const username = localStorage.getItem('username');
    document.getElementById('username').textContent = username;
    
    // 连接WebSocket
    connectWebSocket();
});

// 显示英雄图鉴
async function showHeroes() {
    const heroesModal = document.getElementById('heroesModal');
    const heroesGrid = document.getElementById('heroesGrid');
    heroesGrid.innerHTML = ''; // 清空现有内容

    try {
        const response = await fetch('http://localhost:8081/heroes', {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });
        const heroes = await response.json();

        heroes.forEach(hero => {
            const heroCard = document.createElement('div');
            heroCard.className = 'hero-card';
            heroCard.onclick = () => showHeroDetail(hero);
            
            const rarityText = ['', '普通', '稀有', '史诗', '传说'][hero.rarity];
            
            heroCard.innerHTML = `
                <h3>${hero.name}</h3>
                <span class="hero-rarity rarity-${hero.rarity}">${rarityText}</span>
                <p>${hero.description}</p>
            `;
            
            heroesGrid.appendChild(heroCard);
        });

        heroesModal.style.display = 'block';
    } catch (error) {
        console.error('Error loading heroes:', error);
        showStatus('加载英雄数据失败', 'error');
    }
}

// 显示英雄详情
function showHeroDetail(hero) {
    const modal = document.getElementById('heroDetailModal');
    document.getElementById('heroDetailName').textContent = hero.name;
    document.getElementById('heroDescription').textContent = hero.description;
    document.getElementById('heroHP').textContent = hero.base_hp;
    document.getElementById('heroATK').textContent = hero.base_atk;
    document.getElementById('heroSpeed').textContent = hero.base_speed;
    document.getElementById('heroPosition').textContent = hero.position === 1 ? '前排' : '后排';
    document.getElementById('heroRarity').textContent = ['', '普通', '稀有', '史诗', '传说'][hero.rarity];

    const skillsContainer = document.getElementById('heroSkills');
    skillsContainer.innerHTML = '';

    hero.skills.forEach(skill => {
        const skillElement = document.createElement('div');
        skillElement.className = 'skill';
        
        const skillType = ['', '普通攻击', '主动技能', '被动技能'][skill.type];
        
        skillElement.innerHTML = `
            <h4>${skill.name}</h4>
            <div class="skill-type">${skillType}${skill.cd > 0 ? ` (CD: ${skill.cd}回合)` : ''}</div>
            <div class="skill-description">${skill.description}</div>
        `;
        
        skillsContainer.appendChild(skillElement);
    });

    modal.style.display = 'block';
}

// 关闭英雄图鉴
function closeHeroes() {
    document.getElementById('heroesModal').style.display = 'none';
}

// 关闭英雄详情
function closeHeroDetail() {
    document.getElementById('heroDetailModal').style.display = 'none';
}

// 显示布阵界面
async function showFormation() {
    const formationModal = document.getElementById('formationModal');
    const heroList = document.querySelector('.hero-list');
    heroList.innerHTML = '';

    try {
        // 获取玩家拥有的英雄
        const response = await fetch('http://localhost:8081/heroes/owned', {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });
        const heroes = await response.json();

        // 获取当前布阵
        const formationResponse = await fetch('http://localhost:8081/formation', {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });
        const formation = await formationResponse.json();

        // 清除所有格子的内容和样式
        document.querySelectorAll('.grid-cell').forEach(cell => {
            cell.innerHTML = '';
            cell.classList.remove('occupied');
        });

        // 显示当前布阵
        const positions = formation.positions || [0, 0, 0, 0];
        positions.forEach((heroId, index) => {
            if (heroId) {
                const hero = heroes.find(h => h.id === heroId);
                if (hero) {
                    const cell = document.querySelector(`[data-position="${index}"]`);
                    cell.innerHTML = `
                        <div class="hero-item" draggable="true" ondragstart="drag(event)" data-hero-id="${hero.id}">
                            ${hero.name}
                        </div>
                    `;
                    cell.classList.add('occupied');
                }
            }
        });

        // 生成英雄列表
        heroes.forEach(hero => {
            const heroDiv = document.createElement('div');
            heroDiv.className = 'hero-item';
            heroDiv.draggable = true;
            heroDiv.setAttribute('data-hero-id', hero.id);
            heroDiv.ondragstart = drag;
            heroDiv.textContent = hero.name;
            heroList.appendChild(heroDiv);
        });

        formationModal.style.display = 'block';
    } catch (error) {
        console.error('Error loading formation:', error);
        showStatus('加载布阵信息失败', 'error');
    }
}

// 拖拽相关函数
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("heroId", ev.target.getAttribute('data-hero-id'));
    ev.target.classList.add('dragging');
}

function drop(ev) {
    ev.preventDefault();
    const heroId = ev.dataTransfer.getData("heroId");
    const cell = ev.target.closest('.grid-cell');
    
    // 清除所有拖拽样式
    document.querySelectorAll('.dragging').forEach(el => el.classList.remove('dragging'));
    
    if (cell) {
        // 清除原有英雄
        cell.innerHTML = '';
        // 添加新英雄
        const hero = document.querySelector(`[data-hero-id="${heroId}"]`);
        const heroClone = hero.cloneNode(true);
        heroClone.ondragstart = drag;
        cell.appendChild(heroClone);
        cell.classList.add('occupied');
    }
}

// 保存布阵
async function saveFormation() {
    const positions = [];
    document.querySelectorAll('.grid-cell').forEach((cell, index) => {
        const heroItem = cell.querySelector('.hero-item');
        positions[index] = heroItem ? parseInt(heroItem.getAttribute('data-hero-id')) : null;
    });

    try {
        const response = await fetch('http://localhost:8081/formation', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token'),
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ positions })
        });

        if (response.ok) {
            showStatus('布阵保存成功');
            closeFormation();
        } else {
            const data = await response.json();
            showStatus(data.error || '保存失败', 'error');
        }
    } catch (error) {
        console.error('Error saving formation:', error);
        showStatus('保存布阵失败', 'error');
    }
}

// 关闭布阵界面
function closeFormation() {
    document.getElementById('formationModal').style.display = 'none';
}

// 匹配相关的变量
let isMatching = false;
const matchBtn = document.getElementById('matchBtn');
const matchModal = document.getElementById('matchModal');
const cancelMatch = document.getElementById('cancelMatch');
const matchStatus = document.getElementById('matchStatus');

// 匹配相关的事件监听
matchBtn.addEventListener('click', function() {
    if (!isMatching) {
        startMatching();
    }
});

cancelMatch.addEventListener('click', function() {
    stopMatching();
});

function startMatching() {
    isMatching = true;
    matchBtn.disabled = true;
    matchModal.style.display = 'block';
    matchStatus.textContent = '匹配中...';

    fetch('http://localhost:8081/match', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            matchStatus.textContent = '匹配成功！准备进入战斗...';
            // 获取战斗ID并开始战斗
            const battleId = data.data;  // 从响应中获取战斗ID
            handleBattleStart({ battle_id: battleId });
            // 关闭匹配模态框
            matchModal.style.display = 'none';
        } else {
            matchStatus.textContent = '匹配失败：' + data.message;
            stopMatching();
        }
    })
    .catch(error => {
        console.error('Match error:', error);
        matchStatus.textContent = '匹配出错，请重试';
        stopMatching();
    });
}

function stopMatching() {
    isMatching = false;
    matchBtn.disabled = false;
    matchModal.style.display = 'none';
    matchStatus.textContent = '';
}

function handleBattleStart(content) {
    const battleId = content.battle_id;
    showBattleLoading();
    pollBattleResult(battleId);
}

function pollBattleResult(battleId) {
    console.log('开始轮询战斗结果:', battleId);
    const pollInterval = setInterval(() => {
        fetch(`http://localhost:8081/battle/result/${battleId}`, {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('轮询返回:', data);
            if (data.success && data.result) {
                clearInterval(pollInterval);
                showBattleResult(data.result);
            }
        })
        .catch(error => {
            console.error('轮询错误:', error);
        });
    }, 1000);
}

function showBattleLoading() {
    const battleModal = document.getElementById('battleModal');
    battleModal.style.display = 'block';
}

function showBattleResult(result) {
    // 隐藏加载界面
    document.getElementById('battleModal').style.display = 'none';
    
    // 显示结果界面
    const battleResultModal = document.getElementById('battleResultModal');
    const content = battleResultModal.querySelector('.modal-content');
    content.className = 'modal-content battle-result-container';
    const winnerInfo = battleResultModal.querySelector('.winner-info');
    const battleRounds = battleResultModal.querySelector('.battle-rounds');
    
    // 显示获胜者
    winnerInfo.innerHTML = `
        <h3>🏆 战斗结束 🏆</h3>
        <div class="winner-name">${formatPlayerId(result.winner_id)} 获得胜利！</div>
        <div class="battle-stats">回合数: ${result.total_rounds}</div>
    `;
    
    // 显示战斗过程
    battleRounds.innerHTML = result.rounds.map(round => `
        <div class="round-info">
            <h4>第 ${round.round} 回合</h4>
            ${round.actions.map(action => `
                <div class="action-info">
                    <span class="actor">${formatHeroName(action.actor_id)}</span>
                    <span class="${action.action_type}">
                        ${action.action_type === 'skill' ? '🔥 使用技能' : '⚔️ 普通攻击'}
                    </span>
                    <span class="target">目标: ${formatHeroName(action.target_id)}</span>
                    <span class="damage">
                        -${action.damage}
                        ${action.is_critical ? '<span class="critical">暴击!</span>' : ''}
                    </span>
                </div>
            `).join('')}
        </div>
    `).join('');
    
    battleResultModal.style.display = 'block';
}

function closeBattleResult() {
    document.getElementById('battleResultModal').style.display = 'none';
}

function formatPlayerId(id) {
    return id.startsWith('bot_') ? '机器人' : `玩家 ${id}`;
}

function formatHeroName(heroId) {
    // 临时的英雄名称映射
    const heroNames = {
        'hero_1': '战士',
        'hero_2': '法师',
        'hero_3': '刺客',
        'hero_4': '坦克'
    };
    return heroNames[heroId] || heroId;
} 